<template>
  <div class="data-export">
    <el-dialog 
      v-model="visible" 
      title="导出数据" 
      width="500px"
      @close="handleClose">
      
      <el-form :model="exportConfig" label-width="100px">
        <el-form-item label="导出格式">
          <el-radio-group v-model="exportConfig.format">
            <el-radio label="csv">CSV文件</el-radio>
            <el-radio label="excel">Excel文件</el-radio>
            <el-radio label="json">JSON文件</el-radio>
            <el-radio label="pdf">PDF报告</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="导出内容">
          <el-radio-group v-model="exportConfig.content">
            <el-radio label="current">当前数据</el-radio>
            <el-radio label="filtered">筛选后数据</el-radio>
            <el-radio label="visualization">当前可视化</el-radio>
            <el-radio label="report">整个报表</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item v-if="exportConfig.content === 'visualization'" label="选择图表">
          <el-select v-model="exportConfig.selectedViz" placeholder="选择要导出的图表">
            <el-option 
              v-for="viz in visualizations"
              :key="viz.id"
              :label="viz.title"
              :value="viz.id" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="文件名">
          <el-input v-model="exportConfig.filename" placeholder="导出文件名" />
        </el-form-item>
        
        <el-form-item v-if="exportConfig.format === 'pdf'" label="页面设置">
          <el-radio-group v-model="exportConfig.pageOrientation">
            <el-radio label="portrait">纵向</el-radio>
            <el-radio label="landscape">横向</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item v-if="exportConfig.format === 'excel'" label="包含图表">
          <el-switch v-model="exportConfig.includeCharts" />
        </el-form-item>
      </el-form>
      
      <div class="export-preview">
        <h4>导出预览</h4>
        <div class="preview-info">
          <p>格式: {{ formatLabels[exportConfig.format] }}</p>
          <p>内容: {{ contentLabels[exportConfig.content] }}</p>
          <p>预计大小: {{ estimatedSize }}</p>
        </div>
      </div>
      
      <template #footer>
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleExport" :loading="exporting">
          {{ exporting ? '导出中...' : '开始导出' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { useTableStore } from '../stores/tableStore'
import { exportToCSV } from '../utils/dataUtils'
import { ElMessage } from 'element-plus'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['update:modelValue'])

const tableStore = useTableStore()

// 响应式数据
const visible = ref(props.modelValue)
const exporting = ref(false)
const exportConfig = ref({
  format: 'csv',
  content: 'filtered',
  selectedViz: '',
  filename: '',
  pageOrientation: 'portrait',
  includeCharts: false
})

// 计算属性
const visualizations = computed(() => tableStore.reportConfig.visualizations)

const formatLabels = {
  csv: 'CSV文件',
  excel: 'Excel文件',
  json: 'JSON文件',
  pdf: 'PDF报告'
}

const contentLabels = {
  current: '当前数据',
  filtered: '筛选后数据',
  visualization: '当前可视化',
  report: '整个报表'
}

const estimatedSize = computed(() => {
  let dataCount = 0
  
  switch (exportConfig.value.content) {
    case 'current':
      dataCount = tableStore.currentData.length
      break
    case 'filtered':
      dataCount = tableStore.getFilteredData().length
      break
    case 'visualization':
      dataCount = 100 // 估算
      break
    case 'report':
      dataCount = tableStore.currentData.length * visualizations.value.length
      break
  }
  
  const sizeKB = Math.ceil(dataCount * 0.1) // 粗略估算
  return sizeKB > 1024 ? `${(sizeKB / 1024).toFixed(1)} MB` : `${sizeKB} KB`
})

// 监听器
watch(() => props.modelValue, (newVal) => {
  visible.value = newVal
  if (newVal) {
    // 设置默认文件名
    exportConfig.value.filename = `PowerBI_Export_${new Date().toISOString().slice(0, 10)}`
  }
})

watch(visible, (newVal) => {
  emit('update:modelValue', newVal)
})

// 方法
const handleExport = async () => {
  exporting.value = true
  
  try {
    let data = []
    let filename = exportConfig.value.filename || 'export'
    
    // 获取要导出的数据
    switch (exportConfig.value.content) {
      case 'current':
        data = tableStore.currentData
        break
      case 'filtered':
        data = tableStore.getFilteredData()
        break
      case 'visualization':
        if (exportConfig.value.selectedViz) {
          const viz = visualizations.value.find(v => v.id === exportConfig.value.selectedViz)
          if (viz) {
            data = getVisualizationData(viz)
          }
        }
        break
      case 'report':
        data = await exportReport()
        break
    }
    
    // 根据格式导出
    switch (exportConfig.value.format) {
      case 'csv':
        exportToCSV(data, `${filename}.csv`)
        break
      case 'excel':
        await exportToExcel(data, filename)
        break
      case 'json':
        exportToJSON(data, filename)
        break
      case 'pdf':
        await exportToPDF(data, filename)
        break
    }
    
    ElMessage.success('导出成功！')
    handleClose()
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败，请重试')
  } finally {
    exporting.value = false
  }
}

const getVisualizationData = (viz) => {
  // 根据可视化配置获取数据
  const data = tableStore.getFilteredData()
  
  if (viz.type === 'table') {
    return data
  }
  
  if (viz.type === 'pie') {
    if (viz.config.labelField && viz.config.valueField) {
      return tableStore.aggregateData(
        data,
        [viz.config.labelField],
        [{ field: viz.config.valueField, aggregation: 'sum' }]
      )
    }
  } else if (viz.config.xField && viz.config.yField) {
    return tableStore.aggregateData(
      data,
      [viz.config.xField],
      [{ field: viz.config.yField, aggregation: 'sum' }]
    )
  }
  
  return data
}

const exportToJSON = (data, filename) => {
  const jsonString = JSON.stringify(data, null, 2)
  const blob = new Blob([jsonString], { type: 'application/json' })
  downloadBlob(blob, `${filename}.json`)
}

const exportToExcel = async (data, filename) => {
  // 这里需要引入Excel导出库，如 xlsx
  ElMessage.info('Excel导出功能需要额外的库支持')
  // 暂时用CSV代替
  exportToCSV(data, `${filename}.csv`)
}

const exportToPDF = async (data, filename) => {
  // 这里需要引入PDF生成库，如 jsPDF
  ElMessage.info('PDF导出功能需要额外的库支持')
}

const exportReport = async () => {
  // 导出整个报表的数据
  const reportData = {
    title: tableStore.reportConfig.title,
    description: tableStore.reportConfig.description,
    data: tableStore.getFilteredData(),
    visualizations: visualizations.value.map(viz => ({
      id: viz.id,
      type: viz.type,
      title: viz.title,
      config: viz.config,
      data: getVisualizationData(viz)
    })),
    filters: tableStore.filters,
    exportTime: new Date().toISOString()
  }
  
  return reportData
}

const downloadBlob = (blob, filename) => {
  const url = URL.createObjectURL(blob)
  const link = document.createElement('a')
  link.href = url
  link.download = filename
  link.style.display = 'none'
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
  URL.revokeObjectURL(url)
}

const handleClose = () => {
  visible.value = false
  exporting.value = false
}
</script>

<style scoped>
.export-preview {
  margin-top: 20px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 4px;
}

.export-preview h4 {
  margin-bottom: 12px;
  color: #303133;
}

.preview-info p {
  margin: 4px 0;
  color: #606266;
  font-size: 14px;
}
</style>
